
#include "llvm-c/Disassembler.h"
#include "llvm-c/Target.h"
#include <stdio.h>

static void pprint(int pos, unsigned char *buf, int len, const char *disasm) {
  int i;
  printf("%04x:  ", pos);
  for (i = 0; i < 8; i++) {
    if (i < len) {
      printf("%02x ", buf[i]);
    } else {
      printf("   ");
    }
  }

  printf("   %s\n", disasm);
}

int main(int argc, char const *argv[]) {

  LLVMInitializeAllTargetInfos();
  LLVMInitializeAllTargetMCs();
  LLVMInitializeAllDisassemblers();

//   LLVMDisasmContextRef D = LLVMCreateDisasm("riscv64", NULL, 0, NULL, NULL);
  LLVMDisasmContextRef D =
      LLVMCreateDisasmCPUFeatures("riscv64", "", "", NULL, 0, NULL, NULL);
  char outline[1024];
  int pos;
  char buf[1024];
  int siz = 1024;

  
//          0: 13 01 01 fe                   addi    sp, sp, -32
unsigned int opc =  0xfe010113;
uint8_t *bb = (uint8_t*)(&opc);
    for(int i=0; i<4; i++){
        printf("%02x ", bb[i]);
    }
    printf("\n");

  if (!D) {
    printf("ERROR: Couldn't create disassembler for triple %s\n", "riscv");
    return;
  }

size_t l = LLVMDisasmInstruction(D, bb, 4, 0, outline, sizeof(outline));
printf("L: %d, asm: %s, opc:%x\n", l, outline, opc);

//   pos = 0;  
//   while (pos < siz) {
//     size_t l = LLVMDisasmInstruction(D, buf + pos, siz - pos, 0, outline,
//                                      sizeof(outline));
//     if (!l) {
//       pprint(pos, buf + pos, 1, "\t???");
//       pos++;
//     } else {
//       pprint(pos, buf + pos, l, outline);
//       pos += l;
//     }
//   }

  LLVMDisasmDispose(D);
  return 0;
}
